<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://d3js.org/d3.v6.min.js"></script>
  <style>
    #box{
      background-color: #eee;
    }
  </style>
</head>
<body>
  <svg id='box'></svg>
<script>
  let width = 400,height=400;
  let offset = 20;
  let data = [1000,2000,2300,1200,3000,3400,350];
  // 创造一个线性比例尺
  let scaleLinear = d3.scaleLinear()
                      .domain([0,d3.max(data)]) // 定义域
                      .range([0,height-offset*2])
  console.log(scaleLinear(10))  
  console.log(scaleLinear(35))                   



  let svg = d3.select('#box');
  svg.attr('width',width).attr('height',height)
  let g = svg.append('g');
  let w,s;// w 是柱的宽度 s 是柱之间的缝隙
  s = (width- 2 * offset)/3/data.length;
  w = 2*s;
  g.selectAll('rect')
  .data(data)
  .enter()
  .append('rect')
  .attr('x',function(item,index){
    return offset + w * index + s*(index+1)
  })
  .attr('y',function(item,index){
    return height - offset - scaleLinear(item)
  })
  .attr('width',w)
  .attr('height',function(item){
    return scaleLinear(item)
  })
  .attr('fill',function(item,index){
    return getColor()
  })

  function getColor(){
    let r = Math.floor(Math.random()*256);
    let g = Math.floor(Math.random()*256);
    let b = Math.floor(Math.random()*256);
    return `rgb(${r},${g},${b})`
  }
</script>